// pages/timeline/timeline.js
Page({
  data: {
    currentYear: 0,
    currentMonth: 0,
    selectedDate: '',
    weekDays: ['日', '一', '二', '三', '四', '五', '六'],
    calendarDays: [],
    diaries: {},
    touchStartX: 0,
    touchEndX: 0
  },

  onLoad() {
    const today = new Date();
    this.setData({
      currentYear: today.getFullYear(),
      currentMonth: today.getMonth() + 1,
      selectedDate: today.toISOString().split('T')[0]
    });
    this.generateCalendar();
    this.loadDiaries();
  },

  // 生成日历数据
  generateCalendar() {
    const { currentYear, currentMonth } = this.data;
    const today = new Date();
    
    // 当月第一天
    const firstDay = new Date(currentYear, currentMonth - 1, 1);
    // 当月最后一天
    const lastDay = new Date(currentYear, currentMonth, 0);
    // 第一天是星期几
    const firstDayWeek = firstDay.getDay();
    
    const calendarDays = [];
    
    // 添加上个月末尾的几天
    const prevMonthLastDay = new Date(currentYear, currentMonth - 1, 0).getDate();
    for (let i = firstDayWeek - 1; i >= 0; i--) {
      const day = prevMonthLastDay - i;
      const date = new Date(currentYear, currentMonth - 2, day);
      calendarDays.push(this.createDateData(date, false));
    }
    
    // 添加当月的所有天
    for (let i = 1; i <= lastDay.getDate(); i++) {
      const date = new Date(currentYear, currentMonth - 1, i);
      calendarDays.push(this.createDateData(date, true));
    }
    
    // 添加下个月开始的几天，补满6行(42天)
    const totalCells = 42;
    const remainingCells = totalCells - calendarDays.length;
    
    for (let i = 1; i <= remainingCells; i++) {
      const date = new Date(currentYear, currentMonth, i);
      calendarDays.push(this.createDateData(date, false));
    }
    
    this.setData({ calendarDays });
  },

  // 创建日期数据
  createDateData(date, isCurrentMonth) {
    const year = date.getFullYear();
    const month = date.getMonth() + 1;
    const day = date.getDate();
    const weekDay = date.getDay();
    
    const fullDate = `${year}-${month.toString().padStart(2, '0')}-${day.toString().padStart(2, '0')}`;
    
    const today = new Date();
    const isToday = today.toDateString() === date.toDateString();
    const isWeekend = weekDay === 0 || weekDay === 6;
    
    // 获取该日期的日记关键字
    const diaryData = this.data.diaries[fullDate] || {};
    
    return {
      year,
      month,
      day,
      fullDate,
      weekDay,
      isToday,
      isCurrentMonth,
      isWeekend,
      lunar: this.getLunarDate(date),
      keywords: diaryData.keywords || [],
      hasDiary: !!diaryData.keywords && diaryData.keywords.length > 0
    };
  },

  // 获取农历日期
  getLunarDate(date) {
    const lunarDays = ['初一', '初二', '初三', '初四', '初五', '初六', '初七', '初八', '初九', '初十',
                      '十一', '十二', '十三', '十四', '十五', '十六', '十七', '十八', '十九', '二十',
                      '廿一', '廿二', '廿三', '廿四', '廿五', '廿六', '廿七', '廿八', '廿九', '三十'];
    const day = date.getDate();
    return lunarDays[(day - 1) % 30] || '';
  },

  // 加载日记数据
  loadDiaries() {
    // 模拟日记数据
    const diaries = {
      '2024-10-1': {
        keywords: ['国庆', '旅行'],
        photos: [],
        content: '国庆节第一天，去了天安门广场。'
      },
      '2024-10-4': {
        keywords: ['中秋', '团圆'],
        photos: [],
        content: '中秋节，家人团聚吃月饼。'
      },
      '2024-10-15': {
        keywords: ['工作', '项目'],
        photos: [],
        content: '开始新项目的工作。'
      },
      '2024-10-26': {
        keywords: ['周末', '休息'],
        photos: [],
        content: '周末在家休息。'
      }
    };
    
    this.setData({ diaries });
  },

  // 日期点击事件
  onDateTap(e) {
    const date = e.currentTarget.dataset.date;
    const diaryData = this.data.diaries[date];
    
    if (diaryData && diaryData.keywords && diaryData.keywords.length > 0) {
      wx.navigateTo({
        url: `/pages/diaryDetail/diaryDetail?date=${date}`
      });
    } else {
      wx.showModal({
        title: date,
        content: '这一天还没有日记，是否创建新日记？',
        success: (res) => {
          if (res.confirm) {
            wx.navigateTo({
              url: `/pages/createDiary/createDiary?date=${date}`
            });
          }
        }
      });
    }
  },

  // 跳转到今天
  jumpToToday() {
    const today = new Date();
    this.setData({
      currentYear: today.getFullYear(),
      currentMonth: today.getMonth() + 1
    });
    this.generateThreeMonths();
  },

  // 日期选择器变化
  onDateChange(e) {
    const dateStr = e.detail.value;
    const date = new Date(dateStr);
    
    this.setData({
      currentYear: date.getFullYear(),
      currentMonth: date.getMonth() + 1,
      selectedDate: dateStr
    });
    
    this.generateCalendar();
  },

  // 触摸开始事件
  onTouchStart(e) {
    this.setData({
      touchStartX: e.touches[0].clientX
    });
  },

  // 触摸结束事件
  onTouchEnd(e) {
    const { touchStartX } = this.data;
    const touchEndX = e.changedTouches[0].clientX;
    const diffX = touchEndX - touchStartX;
    
    // 滑动距离阈值，大于50px才触发切换
    if (Math.abs(diffX) > 50) {
      if (diffX > 0) {
        // 向右滑动，切换到上个月
        this.prevMonth();
      } else {
        // 向左滑动，切换到下个月
        this.nextMonth();
      }
    }
  },

  // 上个月
  prevMonth() {
    let { currentYear, currentMonth } = this.data;
    if (currentMonth === 1) {
      currentYear--;
      currentMonth = 12;
    } else {
      currentMonth--;
    }
    
    this.setData({ 
      currentYear, 
      currentMonth,
      selectedDate: `${currentYear}-${currentMonth.toString().padStart(2, '0')}-01`
    });
    this.generateCalendar();
  },

  // 下个月
  nextMonth() {
    let { currentYear, currentMonth } = this.data;
    if (currentMonth === 12) {
      currentYear++;
      currentMonth = 1;
    } else {
      currentMonth++;
    }
    
    this.setData({ 
      currentYear, 
      currentMonth,
      selectedDate: `${currentYear}-${currentMonth.toString().padStart(2, '0')}-01`
    });
    this.generateCalendar();
    this.checkShowBackToToday();
  },

 // 新增：返回今天
backToToday() {
  const today = new Date();
  this.setData({
    currentYear: today.getFullYear(),
    currentMonth: today.getMonth() + 1,
    selectedDate: today.toISOString().split('T')[0]
  });
  this.generateCalendar();
  this.checkShowBackToToday();
},

// 新增：检查是否显示返回今天按钮
checkShowBackToToday() {
  const today = new Date();
  const currentYear = today.getFullYear();
  const currentMonth = today.getMonth() + 1;
  
  // 如果当前显示的月份不是本月，则显示返回今天按钮
  const showBackToToday = !(this.data.currentYear === currentYear && this.data.currentMonth === currentMonth);
  this.setData({ showBackToToday });
}
});